<template>
  <div id="createCrowd" class="form-box">
    <el-drawer
      ref="drawer"
      title="创建人群"
      :visible.sync="dialogData.isShow"
      direction="rtl"
      custom-class="cus-drawer"
      size="890px"
      :modal-append-to-body="false"
    >
      <!--表单开始 编辑/添加-->
      <el-form ref="addForm" :model="form" :rules="rules">
        <!--基本内容-->
        <el-form-item label="人群名称" label-width="80px" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入"
            show-word-limit
            maxlength="40"
          ></el-input>
        </el-form-item>
        <el-form-item label="人群描述" label-width="80px">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入"
            maxlength="300"
            resize="none"
            show-word-limit
          ></el-input>
        </el-form-item>
        <h3 class="title fir-title">
          群成员满足条件
          <i
            class="el-icon-question"
            @click="changeView('wh:system:rules')"
          ></i>
        </h3>
        <!--第一组-->
        <el-form-item
          v-for="(item, index) in form.conditionGroups"
          :key="index"
          class="bottom-none"
        >
          <div v-if="index > 0" class="cus-divider">
            或
          </div>
          <el-card class="cus-form-card" shadow="never">
            <div
              v-for="(item2, index2) in item"
              :key="index2"
              class="cus-card-item"
            >
              <el-row :gutter="5">
                <el-col :span="2">
                  <span>日期</span>
                </el-col>
                <el-col :span="11">
                  <el-date-picker
                    v-model="item2.createTime"
                    type="daterange"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd"
                    :picker-options="pickerOption"
                    :disabled="item2.dataDisabled"
                    @focus="timePickerFocus(item2)"
                  ></el-date-picker>
                </el-col>

                <el-col :offset="9" :span="2">
                  <i
                    class="cus-iconSize el-icon-delete"
                    @click="handleDelOptions(index, index2)"
                  ></i>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="2">
                  <span>条件</span>
                </el-col>
                <el-col :span="4">
                  <el-select
                    v-model="item2.type"
                    placeholder="选择分类"
                    @change="typeChange(item2)"
                  >
                    <el-option
                      v-for="typeItem in typeList"
                      :key="typeItem.value"
                      :label="typeItem.label"
                      :value="typeItem.value"
                    ></el-option>
                  </el-select>
                </el-col>
                <el-col :span="5">
                  <el-select
                    v-model="item2.name"
                    placeholder="选择属性"
                    @change="attributeChange(index, index2, item2, $event)"
                  >
                    <el-option
                      v-for="item in rulesList[item2.type]"
                      :key="item.name"
                      :label="item.name"
                      :value="item.name"
                    ></el-option>
                  </el-select>
                </el-col>
                <el-col :span="4">
                  <el-select
                    v-model="item2.operator"
                    placeholder="选择规则"
                    @visible-change="ruleSelectShow(item2, $event)"
                  >
                    <template v-if="rulesList[item2.type]">
                      <el-option
                        v-for="operatorsItem in item2.operatorsArray"
                        :key="operatorsItem.dictValue"
                        :label="operatorsItem.dictLabel"
                        :value="operatorsItem.dictValue"
                      ></el-option>
                    </template>
                  </el-select>
                </el-col>
                <el-col :span="8">
                  <template v-if="rulesList[item2.type]">
                    <!-- 最终条件判断 包括输入框 单选框 多选框 计数器 日期选择器-->
                    <el-input
                      v-if="
                        form.conditionGroups[index][index2].inputType ===
                          'INPUT_STRING'
                      "
                      v-model="item2.value"
                      placeholder="请输入"
                      key="INPUT_STRING"
                    ></el-input>
                    <el-select
                      v-else-if="
                        form.conditionGroups[index][index2].inputType ===
                          'SELECT'
                      "
                      v-model="item2.value"
                      key="SELECT"
                    >
                      <el-option
                        v-for="finalItem in item2.valueList"
                        :key="finalItem.name"
                        :label="finalItem.name"
                        :value="finalItem.value"
                      ></el-option>
                    </el-select>
                    <el-input-number
                      key="INPUT_NUMBER"
                      v-else-if="
                        form.conditionGroups[index][index2].inputType ===
                          'INPUT_NUMBER'
                      "
                      v-model="item2.value"
                      size="mini"
                      class="input-num"
                      :min="0"
                      label="描述文字"
                    ></el-input-number>
                    <el-select
                      key="MULTI_SELECT"
                      v-else-if="
                        form.conditionGroups[index][index2].inputType ===
                          'MULTI_SELECT'
                      "
                      v-model="item2.value"
                      multiple
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="finalItem in item2.valueList"
                        :key="finalItem.value"
                        :label="finalItem.name"
                        :value="finalItem.value"
                      >
                      </el-option>
                    </el-select>
                    <el-date-picker
                      key="DATE_RANGE"
                      v-else-if="
                        form.conditionGroups[index][index2].inputType ===
                          'DATE_RANGE'
                      "
                      v-model="item2.value"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      value-format="yyyy-MM-dd"
                    >
                    </el-date-picker>
                  </template>
                </el-col>
              </el-row>
            </div>
            <el-button
              v-if="item.length < 3"
              icon="el-icon-plus"
              @click="addAndOptions(index)"
            >
              且条件
            </el-button>
          </el-card>
        </el-form-item>
        <!--添加条件按钮-->
        <el-form-item>
          <el-button
            v-if="this.form.conditionGroups.length < 3"
            type="warning"
            class="cus-form-btn"
            icon="el-icon-plus"
            plain
            @click="addOrOption"
          >
            或条件
          </el-button>
          <div class="card-description">
            当前满足此条件的用户量：{{ peopleNum }}人（{{ peoplePercentage }}%）
            <el-button @click="searchStudent" v-if="!searchPeopleFlag">
              查询满足条件学员数量
            </el-button>
            <el-button v-else>正在查询中...</el-button>
          </div>
        </el-form-item>
        <!--状态-->
        <h3 class="title">
          操作状态
        </h3>
        <div class="status-line">
          启用
          <el-switch v-model="form.enabled" active-color="#1DC8A4"></el-switch>
        </div>
      </el-form>
      <!--底部菜单组-->
      <div class="cus-drawer_footer">
        <div class="sub-button">
          <el-button type="success" plain @click="handleClose">
            取 消
          </el-button>
          <el-button type="success" :loading="loading" @click="confirm">
            确定
          </el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { sysNormalDisable } from '@utils/dictionariesFunc'
import { setTimeout } from 'timers'
import {
  getPeopleRuleRequest,
  searchStudentAPI,
  getPeopleValueRequest,
  createPeopleRequest
} from '@/api/userManagement/userManageAPI'
export default {
  name: 'CreateCrowd',
  msg: '人群管理/创建人群',
  props: ['dialogData'],
  data() {
    return {
      loading: false,
      form: {
        enabled: true, // 操作状态
        name: '', // 人群名称
        description: '', // 人群描述
        // 或条件数组
        conditionGroups: [
          // 且条件数组
          [
            {
              createTime: '', // 日期
              type: '', // 条件类别
              name: '', //属性
              operator: '', // 规则
              inputType: '', // 输入框类型
              code: ''
            }
          ]
        ]
      },
      rules: {
        name: [{ required: true, message: '请输入人群名称' }]
      },
      typeList: [
        // 分类
        { label: '行为类别', value: 'ACTION' },
        { label: '身份类别', value: 'IDENTITY' },
        { label: '运营类别', value: 'OPERATION' }
      ],
      // 属性规则数组
      rulesList: {
        ACTION: [],
        IDENTITY: [],
        OPERATION: []
      },
      selectCode: '', // 选中的属性code值
      operatorsArray: [],
      groupOperatorDic: [], //运算符字典
      pickerOption: this.pickerDisabled(), // 限制时间配置
      timeDisable: 365, // 限制时间天数
      dataDisabled: false, // 日期选择是否禁用
      peopleNum: 0, // 符合人数
      peoplePercentage: 0, // 人数百分比
      pickMinDate: '', // 选中的最小日期
      searchPeopleFlag: false,
      searchStudentParams: null
    }
  },
  mounted() {
    this.getPeopleRule()
    this.getGroupOperatorDic()
  },
  methods: {
    // 获取人群规则
    getPeopleRule() {
      getPeopleRuleRequest((response) => {
        this.rulesList.ACTION = response.ACTION
        this.rulesList.IDENTITY = response.IDENTITY
        this.rulesList.OPERATION = response.OPERATION
      })
    },
    // 分类改变
    typeChange(item2) {
      item2.operator = ''
      item2.name = ''
      item2.inputType = ''
      item2.code = ''
      this.timeDisable = 365
      item2.dataDisabled = false
    },
    // 添加或条件
    addOrOption() {
      this.pickMinDate = ''
      let andOptions = [
        {
          createTime: '', // 日期
          type: '', // 条件类别
          name: '', //属性
          operator: '', // 规则
          inputType: '', // 输入框类型
          code: ''
        }
      ]
      this.form.conditionGroups.push(andOptions)
    },
    // 删除条件项
    handleDelOptions(index, index2) {
      let orIndex = index // 或条件索引
      let andIndex = index2 // 且条件索引
      // 如果只有一个且条件 且条件里面只有一个或条件 则不能删除
      if (
        this.form.conditionGroups.length === 1 &&
        this.form.conditionGroups[orIndex].length === 1
      )
        return
      if (this.form.conditionGroups[orIndex].length === 1) {
        // 只有一个且条件时 删除整个或条件
        this.form.conditionGroups.splice(orIndex, 1)
      } else {
        // 有多个且条件 根据索引删除且条件
        this.form.conditionGroups[orIndex].splice(andIndex, 1)
      }
    },
    // 添加且条件
    addAndOptions(index) {
      this.pickMinDate = ''
      let andOptionItem = {
        createTime: '', // 日期
        type: '', // 条件类别
        name: '', //属性
        operator: '', // 规则
        inputType: '', // 输入框类型
        code: ''
      }
      this.form.conditionGroups[index].push(andOptionItem)
    },
    // 取消按钮
    handleClose() {
      this.dialogData.isShow = false
    },
    /* 确定 */
    confirm() {
      this.$refs.addForm.validate((valid) => {
        let hasCreateTime = true
        if (!valid) return
        let form = JSON.parse(JSON.stringify(this.form))
        for (let item in form.conditionGroups) {
          form.conditionGroups[item].map((item2, index2) => {
            if (item2.createTime && item2.createTime.length !== 0) {
              item2.startTime = item2.createTime[0]
              item2.endTime = item2.createTime[1]
              delete item2.createTime
            } else {
              // 不等于运营标签规则
              if (item2.code !== '0001' && item2.name !== '') {
                hasCreateTime = false
              }
            }
            if (item2.value instanceof Array) {
              item2.value = item2.value.join(',')
            }
            if (!item2.value) {
              item2 = {}
            }
            if (Object.keys(item2).length === 0) {
              form.conditionGroups[item].splice(index2, 1)
            }
            delete item2.operatorsArray
            delete item2.valueList
            delete item2.dataDisabled
          })
        }
        if (!hasCreateTime) {
          this.$alert(`请补全必填的时间范围！`, '系统提示', {
            confirmButtonText: '确定'
          })
          return
        }
        // let url = '/student-groups'
        let params = form
        createPeopleRequest(
          params,
          (response) => {
            this.$emit('refresh')
            this.dialogData.isShow = false
          },
          (response) => {
            this.$message({
              message: response.message,
              type: 'warning'
            })
            this.dialogData.isShow = false
          }
        )
      })
    },
    /* 跳转页面 */
    changeView(name) {
      this.$router.push({ name: name })
    },
    // 查询满足条件学员数量
    searchStudent() {
      this.searchPeopleFlag = true
      let form = JSON.parse(JSON.stringify(this.form))
      for (let item in form.conditionGroups) {
        form.conditionGroups[item].map((item2) => {
          item2.startTime = item2.createTime[0]
          item2.endTime = item2.createTime[1]
          delete item2.createTime
          delete item2.inputType
          delete item2.type
          delete item2.name
          delete item2.operatorsArray
          delete item2.valueList
          delete item2.dataDisabled
          if (item2.value instanceof Array) {
            item2.value = item2.value.join(',')
          }
        })
      }
      let params = {
        conditions: JSON.stringify(form.conditionGroups)
      }
      this.searchStudentParams = params
      this.searchStudentRequest(this.searchStudentParams)
    },
    searchStudentRequest(params) {
      let timeFlag = true
      searchStudentAPI(
        params,
        (response) => {
          if (response.result) {
            this.searchPeopleFlag = false
            let peopleNum = response.usernum
            let allPeopleNum = response.usersumnum
            this.peopleNum = peopleNum
            if (allPeopleNum === 0) {
              this.peoplePercentage = 0
              return
            }
            this.peoplePercentage = (
              (parseInt(peopleNum) / parseInt(allPeopleNum)) *
              100
            ).toFixed(3)
          } else {
            this.throttleSearchStudent()
          }
        },
        (response) => {
          this.searchPeopleFlag = false
          this.$message({
            message: response.message,
            type: 'warning'
          })
        }
      )
    },
    throttleSearchStudent() {
      if (!this.dialogData.isShow) {
        return
      }
      let timeFlag = true
      if (!timeFlag) {
        return
      }
      timeFlag = true
      setTimeout(() => {
        this.searchStudentRequest(this.searchStudentParams)
        timeFlag = false
      }, 10000)
    },
    // 选择属性
    attributeChange(index, index2, conditionItem, val) {
      conditionItem.operator = ''
      delete conditionItem.value
      let selectVal = val // 选中的属性
      let rulesList = this.rulesList
      for (let item in rulesList) {
        rulesList[item].map((item2) => {
          if (item2.name === selectVal) {
            this.selectCode = item2.code
            this.timeDisable = item2.cycle
            if (item2.cycle === '0') {
              item2.createTime = ''
              conditionItem.dataDisabled = true
            } else {
              conditionItem.dataDisabled = false
            }
            if (conditionItem.createTime) {
              let startData = new Date(conditionItem.createTime[0]).getTime()
              let endData = new Date(conditionItem.createTime[1]).getTime()
              if (endData - startData > item2.cycle * 24 * 3600 * 1000) {
                conditionItem.createTime = []
                this.$alert(
                  `该规则下时间范围不得大于${item2.cycle}天，请重新选择！`,
                  '系统提示',
                  {
                    confirmButtonText: '确定'
                  }
                )
              }
            }

            this.form.conditionGroups[index][index2].inputType = item2.inputType
            this.form.conditionGroups[index][index2].code = item2.code
            let tempArray = item2.operators.split(',')
            let operatorsArray = []
            tempArray.forEach((value) => {
              let operatorItem = this.filterGroupOperatorDic(value)
              operatorsArray.push(operatorItem)
            })
            conditionItem.operatorsArray = operatorsArray
          }
        })
      }
    },
    // 选择规则
    ruleSelectShow(conditionItem, e) {
      if (e) {
        getPeopleValueRequest(conditionItem, (response) => {
          if (response) {
            conditionItem.valueList = response
          }
        })
      }
    },
    // 循环匹配运算符
    filterGroupOperatorDic(value) {
      let operatorsArray = []
      let operatorItem = this.groupOperatorDic.find((item) => {
        return item.dictValue === value
      })
      return operatorItem
    },
    // 获取运算符字典
    async getGroupOperatorDic() {
      let groupOperatorDic = await sysNormalDisable(
        'student_group_condition_operator'
      )
      this.groupOperatorDic = groupOperatorDic
    },
    // 日期选择器限制条件
    pickerDisabled() {
      const that = this
      return {
        disabledDate(time) {
          let pickMinDate = that.pickMinDate
          let oneDayTime = 24 * 60 * 60 * 1000
          let day = that.timeDisable * oneDayTime
          if (pickMinDate) {
            let timePickDisable =
              time.getTime() > pickMinDate.getTime() + day - oneDayTime ||
              time.getTime() < pickMinDate.getTime() - day + oneDayTime
            return timePickDisable
          } else {
            return false
          }
        },
        onPick({ maxDate, minDate }) {
          let pickMinDate = minDate
          that.pickMinDate = pickMinDate
        }
      }
    },
    timePickerFocus(conditionItem) {
      const that = this
      that.timeDisable = 365
      this.pickMinDate = ''
      let rulesList = this.rulesList
      for (let item in rulesList) {
        rulesList[item].map((item2) => {
          if (item2.code === conditionItem.code) {
            that.timeDisable = item2.cycle
          }
        })
      }
    }
  }
}
</script>

<style lang="less">
#createCrowd {
  .cus-drawer {
    .el-form {
      padding-bottom: 50px;
    }

    .cus-form-item {
      margin-left: 20px;
      height: 16px;
      line-height: 16px;
      font-size: 16px;
      color: #0d1636;
      font-weight: 600;
      padding-left: 3px;
      border-left: 3px solid #1dc8a4;
    }

    .fir-title {
      margin-top: 22px !important;
      margin-bottom: 14px !important;

      i {
        cursor: pointer;
      }
    }

    .bottom-none {
      margin-bottom: 0 !important;
    }

    .card-description {
      float: right;
      font-size: 13px;
    }

    .cus-form-card {
      background-color: #f2f4f5;

      .el-button {
        margin-top: 10px;
        padding: 4px;
        border-radius: 2px;
        font-family: 'Microsoft YaHei';
        font-size: 14px;
      }

      .el-input__inner {
        height: 28px;
        line-height: 28px;
      }

      .el-date-editor {
        .el-range__icon,
        .el-range-separator,
        .el-range__close-icon {
          line-height: 17px;
        }
      }

      .el-date-editor--daterange.el-input__inner {
        width: 100% !important;
      }

      .cus-iconSize {
        color: #99a9bf;
        font-size: 20px;

        &:hover {
          cursor: pointer;
          color: #0d1636;
        }
      }
    }

    .cus-form-btn {
      padding: 4px 5px;
    }

    .cus-form-switch {
      margin: 20px 10px;
      margin-bottom: 60px;
    }

    .el-col {
      border-radius: 4px;
    }

    .bg-purple-dark {
      background: #99a9bf;
    }

    .bg-purple {
      background: #d3dce6;
    }

    .bg-purple-light {
      background: #e5e9f2;
    }

    .grid-content {
      border-radius: 4px;
      min-height: 36px;
    }

    .row-bg {
      padding: 10px 0;
      background-color: #f9fafc;
    }
    .input-num {
      .el-input-number__increase,
      .el-input-number__decrease {
        background: #fff;
      }
    }
    @import url('~@common/style/textarea.less');
  }
}
</style>
